package org.argus.job.server.system.management.controller;

import java.io.File;

import javax.servlet.http.HttpServletResponse;

import org.argus.common.core.domain.R;
import org.argus.job.common.model.InstanceDetail;
import org.argus.job.common.model.InstanceInfo;
import org.argus.job.common.utils.JobFileUtils;
import org.argus.job.server.local.persistent.StringPage;
import org.argus.job.server.system.instance.InstanceLogService;
import org.argus.job.server.system.instance.InstanceService;
import org.argus.job.server.system.management.model.InstanceSearchReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

/**
 * @Author 刘文/Cliff Liu
 * @Date 2024/10/31
 */
@RestController
@RequestMapping("/instance/v1/instance")
public class InstanceInfoController {

    @Autowired
    private InstanceService instanceService;

    @Autowired
    private InstanceLogService instanceLogService;

    @GetMapping("/page")
    public R<Page<InstanceInfo>> page(InstanceSearchReq searchReq, Page page) {
        return R.ok(instanceService.page(searchReq, page));
    }

    @GetMapping("/detail/{appId}/{instanceId}")
    public R<InstanceDetail> detail(@PathVariable("appId") Long appId, @PathVariable("instanceId") Long instanceId) {
        return R.ok(instanceService.getInstanceDetail(appId, instanceId));
    }

    @GetMapping("/log")
    public R<StringPage> getInstanceLog(Long appId, Long instanceId, Long index) {
        return R.ok(instanceLogService.fetchInstanceLog(appId, instanceId, index));
    }

    @PostMapping("/retry/{instanceId}")
    public R<Void> retryInstance(@PathVariable("instanceId") Long instanceId) {
        instanceService.retryInstance(instanceId);
        return R.ok();
    }

    @GetMapping("/downloadLog/{instanceId}")
    public void downloadLogFile(@PathVariable("instanceId") Long instanceId , HttpServletResponse response) throws Exception {
        File file = instanceLogService.downloadInstanceLog(instanceId);
        JobFileUtils.file2HttpResponse(file, response);
    }

    @PutMapping("/stop/{instanceId}")
    public R<Void> stopInstance(@PathVariable("instanceId") Long instanceId) {
        instanceService.stopInstance(instanceId);
        return R.ok();
    }
}
